$(function(){			
		$("#btn_confirm_add").hide();
			var userInfo = {
				userId: "1111",
				fileType: "0"
			}; //用户会话信息
			var chunkSize = 5000 * 1024; //分块大小
			var uniqueFileName = null; //文件唯一标识符
			var md5Mark = null;
			var removeChildNodes = function($, own) {
				if($ == null) {
					return;
				}
				while($.hasChildNodes()) {
					$.removeChild($.firstChild);
				}
				if(own) {
					$.parentNode.removeChild($);
				}
			};

			function getServer(type) { //测试用，根据不同类型的后端返回对应的请求地址
				switch(type) {
					case "php":
						return "./serverPHP/fileUpload.php"
					case "node":
						return "http://localhost:3000/fileUpload";
					case "java":
						return "http://101.37.82.219:8087/elink_uploader/fileUpload";
					case "dubbo":
						return "http://127.0.0.1:8888/fileUpload";
				}
			}

			var backEndUrl = getServer("java");

			WebUploader.Uploader.register({
				"before-send-file": "beforeSendFile",
				"before-send": "beforeSend",
				"after-send-file": "afterSendFile"
			}, {
				beforeSendFile: function(file) {
					//秒传验证
					var task = new $.Deferred();
					var start = new Date().getTime();
					(new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function(percentage) {
						console.log(percentage);
					}).then(function(val) {
						console.log("总耗时: " + ((new Date().getTime()) - start) / 1000);

						md5Mark = val;
						userInfo.md5 = val;
						console.log(1);
						$.ajax({
							type: "POST",
							url: backEndUrl,
							data: {
								status: "md5Check",
								md5: val
							},
							cache: false,
							timeout: 1000 //todo 超时的话，只能认为该文件不曾上传过
								,
							dataType: "json"
						}).then(function(data, textStatus, jqXHR) {

							//console.log(data);

							if(data.ifExist) { //若存在，这返回失败给WebUploader，表明该文件不需要上传
								task.reject();
								uploader.skipFile(file);
								file.path = data.path;
								UploadComlate(file);
							} else {
								task.resolve();
								//拿到上传文件的唯一名称，用于断点续传
								uniqueFileName = md5(file.name + file.type + file.lastModifiedDate + file.size);
							}
						}, function(jqXHR, textStatus, errorThrown) { //任何形式的验证失败，都触发重新上传
							task.resolve();
							//拿到上传文件的唯一名称，用于断点续传
							uniqueFileName = md5(file.name + file.type + file.lastModifiedDate + file.size);
						});
					});
					return $.when(task);
				},
				beforeSend: function(block) {
					//分片验证是否已传过，用于断点续传
					var task = new $.Deferred();
					console.log(2);
					$.ajax({
						type: "POST",
						url: backEndUrl,
						data: {
							status: "chunkCheck",
							name: uniqueFileName,
							chunkIndex: block.chunk,
							size: block.end - block.start,
							fileType: userInfo.fileType
						},
						cache: false,
						timeout: 1000 //todo 超时的话，只能认为该分片未上传过
							,
						dataType: "json"
					}).then(function(data, textStatus, jqXHR) {
						if(data.ifExist) { //若存在，返回失败给WebUploader，表明该分块不需要上传
							task.reject();
						} else {
							task.resolve();
						}
					}, function(jqXHR, textStatus, errorThrown) { //任何形式的验证失败，都触发重新上传
						task.resolve();
					});

					return $.when(task);
				},
				afterSendFile: function(file, data) {
					var chunksTotal = 0;
					if((chunksTotal = Math.ceil(file.size / chunkSize)) > 1) {
						//合并请求
						var task = new $.Deferred();
						console.log(3);
						$.ajax({
							type: "POST",
							url: backEndUrl,
							data: {
								status: "chunksMerge",
								name: uniqueFileName,
								chunks: chunksTotal,
								ext: file.ext,
								md5: md5Mark,
								fileType: userInfo.fileType,
								fileName: file.name
							},
							cache: false,
							dataType: "json"
						}).then(function(data, textStatus, jqXHR) {

							//todo 检查响应是否正常

							task.resolve();
							file.path = data.path;
							UploadComlate(file);

						}, function(jqXHR, textStatus, errorThrown) {
							task.reject();
						});

						return $.when(task);
					} else {
						file.path = data.path;
						UploadComlate(file);
					}
				}
			});

			var uploader = WebUploader.create({
				swf: "Uploader.swf",
				server: backEndUrl,
				pick: "#picker",
				resize: false,
				dnd: "#theList",
				paste: document.body,
				disableGlobalDnd: true,
				thumb: {
					width: 100,
					height: 100,
					quality: 70,
					allowMagnify: true,
					crop: true
						//, type: "image/jpeg"
				}
				//				, compress: {
				//					quality: 90
				//					, allowMagnify: false
				//					, crop: false
				//					, preserveHeaders: true
				//					, noCompressIfLarger: true
				//					,compressSize: 100000
				//				}
				,
				compress: false,
				prepareNextFile: true,
				chunked: true,
				chunkSize: chunkSize,
				threads: true,
				formData: function() {
					return $.extend(true, {}, userInfo);
				},
				fileNumLimit: 1,
				fileSingleSizeLimit: 1000 * 1024 * 1024 * 1024,
				duplicate: true
			});

			//			<button id="upload" class="btn btn-default">开始上传</button>
			//			<button id="cancel" class="btn btn-default">取消</button>
			uploader.on("fileQueued", function(file) {
				$(".webuploader-pick").text("重新上传");
				//				$("#theList").append('<li id="' + file.id + '">' +
				//					'<img /><span>' + file.name + '</span><span class="itemUpload">上传</span><span class="itemStop">暂停</span><span class="itemDel">删除</span>' +
				//					'<div class="percentage"></div>' +
				//					'</li>');
				$("#uploader").append(
					'<button id="itemUpload" class="btn btn-default">开始上传</button><button id="itemStop" class="btn btn-default">暂停上传</button>'
				);
				$("#theList").append('<li id="' + file.id + '">' +
//					'<img />' +
					'<div class="percentage"></div>' +
					'</li>');
				var $img = $("#" + file.id).find("img");

				uploader.makeThumb(file, function(error, src) {
					if(error) {
						$img.replaceWith("<span>无预览</span>");
					}

					$img.attr("src", src);
				});
				$("#itemFileName").text(file.name);
			});
			$("#picker").click(function() {
				if($("#picker").attr("resetValue") == 1) {
					uploader.reset();
					removeChildNodes(document.getElementById("theList"));
					removeChildNodes(document.getElementById("itemUpload"), true);
					removeChildNodes(document.getElementById("itemStop"), true);
					removeChildNodes(document.getElementById("itemSuccess"), true);
				} else {
					$("#picker").attr("resetValue", 1);
				}
			});
			$("#uploader").on("click", "#itemUpload", function() {
				uploader.upload();

				//"上传"-->"暂停"
				$(this).hide();
				$("#itemStop").show();
			});

			$("#uploader").on("click", "#itemStop", function() {
				uploader.stop(true);
				//"暂停"-->"上传"
				$(this).hide();
				$("#itemUpload").show().text("继续上传");
			});

			//todo 如果要删除的文件正在上传（包括暂停），则需要发送给后端一个请求用来清除服务器端的缓存文件 未实现
			$("#uploader").on("click", "#itemDel", function() {
				uploader.removeFile($(this).parent().attr("id")); //从上传文件列表中删除
				$(this).parent().remove(); //从上传列表dom中删除
			});
//			uploader.on("uploadProgress", function(file, percentage){
//				$("#" + file.id + " .percentage").text(percentage * 100 + "%");
//			});

			// 文件上传过程中创建进度条实时显示。
			uploader.on('uploadProgress', function(file, percentage) {
				var $li = $('#' + file.id),
					$percent = $li.find('.progress .progress-bar');
				// 避免重复创建
				if(!$percent.length) {
					$percent = $('<div id="progressParent" class="progress progress-striped active">' +
						'<div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;">' +
						'</div>' +
						'</div>').appendTo($li).find('.progress-bar');
				}

//				$li.find('p.state').text('上传中');
				$percent.css('width', percentage * 100 + '%');
				$("#progressBar").css('width',percentage * 100 + '%');
//				$("#" + file.id + " .percentage").text(percentage * 100 + "%");
				$("#progressBar").text(parseInt((parseFloat($("#progressBar").css("width")) / parseFloat($("#progressParent").css("width")) * 100))+ "%");
//				$("#" + file.id + " .percentage").text(parseInt((parseFloat($("#progressBar").css("width")) / parseFloat($("#progressParent").css("width")) * 100)));
			});

			function UploadComlate(file) {
//				$("#" + file.id + " .percentage").text("上传完毕");
				$("#uploader").append(
						'<button id="itemSuccess" class="btn btn-default">上传成功</button>'
					);
//				console.log(file.size);
				$("#progressBar").text("100%");
//				alert(file.path);
				$("#url").val(file.path);
				$("#fileSize").val(file.size);
				$("#itemStop").hide();
				$("#itemUpload").hide();
				$("#btn_confirm_add").show();
			}
});